package com.bmd.backgroundmanger.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bmd.backgroundmanger.commons.Result;
import com.bmd.backgroundmanger.entity.Category;
import com.bmd.backgroundmanger.service.ICategoryService;
import com.bmd.backgroundmanger.utils.FileUploadUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类管理Controller
 */
@RestController
@RequestMapping("/category")
@Tag(name = "分类管理")
public class CategoryController {

    @Resource
    private ICategoryService categoryService;

    @Value("${file.upload-path:/uploads/}")
    private String uploadPath;

    @PostMapping("/selectPageData")
    @Operation(summary = "分页查询分类列表")
    public Result<Map<String, Object>> selectPageData(
            int page,
            int size,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status", required = false) Integer status) {
        
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(StringUtils.hasLength(name), Category::getName, name);
        wrapper.eq(status != null, Category::getStatus, status);
        wrapper.orderByAsc(Category::getSortOrder)
               .orderByDesc(Category::getCreateTime);
        
        Page<Category> p = new Page<>(page, size);
        Page<Category> categoryPage = categoryService.page(p, wrapper);
        
        map.put("categories", categoryPage.getRecords());
        map.put("total", categoryPage.getTotal());
        return Result.success(map);
    }

    @GetMapping("/getAllCategories")
    @Operation(summary = "获取所有分类")
    public Result<List<Category>> getAllCategories() {
        List<Category> categories = categoryService.list();
        return Result.success(categories);
    }

    @PostMapping("/updateAndSave")
    @Operation(summary = "新增/编辑分类")
    public Result<String> updateAndSave(@RequestBody Category category) {
        if (category.getCategoryId() == null) {
            categoryService.save(category);
            return Result.success("新增成功!");
        } else {
            categoryService.updateById(category);
            return Result.success("修改成功!");
        }
    }

    @DeleteMapping("/delDataById/{id}")
    @Operation(summary = "根据ID删除分类")
    public Result<String> delDataById(@PathVariable Integer id) {
        categoryService.removeById(id);
        return Result.success("删除成功");
    }

    @PostMapping("/delDataByIds")
    @Operation(summary = "批量删除分类")
    public Result<String> delDataByIds(@RequestBody List<Integer> ids) {
        categoryService.removeBatchByIds(ids);
        return Result.success("批量删除成功!");
    }

    @PostMapping("/uploadIcon")
    @Operation(summary = "上传分类图标")
    public Result<Map<String, String>> uploadIcon(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件!");
            }

            // 验证文件大小 (2MB)
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error("图片大小不能超过2MB!");
            }

            // 上传文件
            String fileName = FileUploadUtil.uploadFile(file, uploadPath + "icons");
            String fileUrl = "/uploads/icons/" + fileName;

            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("fileName", fileName);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("图标上传失败: " + e.getMessage());
        }
    }
} 